<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"></c:set>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>社区云超市 - 首页</title>
    <link rel="stylesheet" href="${contextPath}/static/statistics/css/bootstrap.min.css">
    <style type="text/css">
        .center-block {
            display: block;
            margin-left: auto;
            margin-right: auto;
        }
        .my-nav {
            margin-top: 3px;
            background: linear-gradient(#1e4bdd, #bc6bff);
        }
        .my-table-responsive {
            background-color:#FFF;
            margin-top: 10px;
            overflow-y: auto;
            border: 1px solid #ddd;
            height: 300px;
        }
        .select-product-input-div{
            margin-top: 10px;
        }
        .payWayIcon {
            width: 100px;
            height: 100px;
            margin-left: 14px;
            margin-top: 6px;
        }
        table{font-size: 18px;}
    </style>
</head>
<body style="background: rgba(165, 161, 161, 0.07);">
<div class="container my-container">
    <div class="row" id="app">
        <div class="col-sm-12 col-xs-12 col-md-1 col-lg-1"></div>
        <div class="col-sm-12 col-xs-12 col-md-10 col-lg-10">
            <div class="bs-example">
                <nav id="navbar-example" class="navbar navbar-default navbar-static my-nav">
                    <div class="container-fluid">
                        <div class="navbar-header">
                            <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target=".bs-example-js-navbar-collapse">
                                <span class="sr-only">Toggle navigation</span>
                                <span class="icon-bar"></span>
                                <span class="icon-bar"></span>
                                <span class="icon-bar"></span>
                            </button>
                            <a class="navbar-brand" href="#" style="color: white;">社区云超市</a>
                        </div>
                        <div class="navbar-brand" style="color: white; margin: 0 auto; width: 40%; text-align: center">本日销售额：{{totalPrices}}元</div>
                        <div class="collapse navbar-collapse bs-example-js-navbar-collapse">
                            <ul class="nav navbar-nav navbar-right">
                                <li id="fat-menu" class="dropdown">
                                    <a id="drop3" style="color: white;" href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
                                        ${user.shopName}-${user.shopType}-${user.userName}
                                        <span class="caret"></span>
                                    </a>
                                    <ul class="dropdown-menu" aria-labelledby="drop3">
                                        <%--<li><a href="#">商品管理</a></li>
                                        <li><a href="#">商品入库</a></li>--%>
                                        <li role="separator" class="divider"></li>
                                        <li><a href="${contextPath}/supermarket/login">退出登陆</a></li>
                                    </ul>
                                </li>
                            </ul>
                        </div><!-- /.nav-collapse -->
                    </div><!-- /.container-fluid -->
                </nav> <!-- /navbar-example -->
            </div> <!-- /example -->
            <div class="table-responsive my-table-responsive">
                <table class="table table-hover">
                    <thead>
                    <tr>
                        <th>序号</th>
                        <th>商品</th>
                        <th>数量</th>
                        <th></th>
                        <th>售价</th>
                        <%--<th>团购价</th>--%>
                        <th>小计</th>
                        <th>库存</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr v-for="(product, index) in productList">
                        <td>{{index+1}}</td>
                        <td><a title="查看图片" @click="showProdImageFn(index)" href="javascript:void(0);">{{product.prodName}}</a></td>
                        <td><div contenteditable="true" :id="'product_quantity_'+index" @blur="changeQuantity(index,'${user.shopType}')" :name="product.stock" onkeydown="onTQuantityKeyDown(this.id)">{{product.quantity}}</div></td>
                        <td><div :id="'product_priceType_'+index"></div></td>
                        <td><div contenteditable="false" :id="'product_price_'+index"  @click="price(index,product)">{{product.rtlPrice}}</div></td>
                        <td class="hide"><input :id="'price_'+index" :value="product.rtlPrices" /></td>
                        <td>{{accMul(product.quantity,product.rtlPrice)}}</td>
                        <td>{{product.stock}}</td>
                        <td><button class="btn btn-danger btn-xs" @click="deleteProduct(index)">删除</button></td>
                    </tr></tbody>
                </table>
            </div>
            <div style="text-align: right;margin-top: 5px; font-size: 18px;">
                <input type="text" style="width: 120px;height: 25px; margin-right: 230px;" max="13" v-model="mobile" class="hide" id="privilege_mobile_input">
                <button id="privilege_mobile_button" class="btn btn-info btn-xs" @click="privilegeMobile" style="font-size: 15px;  margin-right: 230px;">会员手机号</button>

                <input type="number" style="width: 77px;height: 21px;" v-model="befAmt" min="0" class="hidden" id="privilege_amt_input">
                <button id="privilege_amt_button" class="btn btn-success btn-xs" @click="privilegeAmt" style="font-size: 15px;">立刻优惠</button>合计金额：<span style="color: red;">￥{{totalAmt}}元</span>
            </div>
            <div style="text-align: right;margin-top: 5px; font-size: 18px;">
                实际金额：<span style="color: red;">￥{{accSub(totalAmt , befAmt)}}元</span>
            </div>
            <div class="select-product-input-div row">
                <div class="col-sm-12 col-xs-12 col-md-4 col-lg-4"></div>
                <div class="col-sm-12 col-xs-12 col-md-4 col-lg-4">
                    <input type="text"  v-model="barCode" id="barCodeInput" name="barCodeInput" maxlength="13"  class="form-control center-block"  placeholder="条形码">
                </div>
                <div class="col-sm-12 col-xs-12 col-md-4 col-lg-4"></div>
            </div>
            <div class="select-product-input-div row">
                <div class="col-sm-12 col-xs-12 col-md-4 col-lg-4"></div>
                <div class="col-sm-12 col-xs-12 col-md-4 col-lg-4">
                    <button class="center-block btn btn-sm btn-primary" @click="addUnknowProduct"><span class="glyphicon glyphicon-plus"></span>添加未知商品</button>
                </div>
                <div class="col-sm-12 col-xs-12 col-md-4 col-lg-4"></div>
            </div>
            <div class="row" style="margin-top: 50px;">
                <div class="col-sm-12 col-xs-12 col-md-4 col-lg-4"></div>
                <div class="col-sm-12 col-xs-12 col-md-4 col-lg-4">
                    <button type="button" id="confirmOrder" @click="confirmOrder"  class="btn btn-warning btn-lg btn-block">确认结算</button>
                </div>
                <div class="col-sm-12 col-xs-12 col-md-4 col-lg-4"></div>
            </div>
        </div>
        <div class="col-sm-12 col-xs-12 col-md-1 col-lg-1"></div>
        <input type="hidden" id="user_id" value="${user.userId}">
        <input type="hidden" id="shop_id" value="${user.shopId}">

        <!-- 查看图片 -->
        <div class="modal fade bs-example-modal-sm" id="showImageModel" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel">
            <div class="modal-dialog modal-sm" role="document">
                <div class="modal-content">
                    <img :src="showProdImage" id="prodImage" class="hidden">
                </div>
            </div>
        </div>
        <!-- 支付 -->
        <div class="modal fade" id="payModal" tabindex="-1" data-backdrop="static" role="dialog" aria-labelledby="gridSystemModalLabel">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h4 class="modal-title" id="gridSystemModalLabel">选择支付方式</h4>
                    </div>
                    <div class="modal-body">
                        <div class="row">
                            <a v-show="payWayInArray('1')" @click="choosePayWay(11)" href="javascript:void(0);" class="button"><img class="payWayIcon" src="${contextPath}/static/image/payWayImage/wechat.png"/></a>
                            <a v-show="payWayInArray('2')" @click="choosePayWay(12)" href="javascript:void(0);" class="button"><img class="payWayIcon" src="${contextPath}/static/image/payWayImage/zhifubao.png"></a>
                            <a v-show="payWayInArray('3')" onclick="layer.msg('暂未开放，敬请期待');" href="javascript:void(0);" class="button"><img class="payWayIcon" src="${contextPath}/static/image/payWayImage/unionpay.png"></a>
                            <a v-show="payWayInArray('4')" @click="choosePayWay(6)" href="javascript:void(0);" class="button"><img class="payWayIcon" src="${contextPath}/static/image/payWayImage/pos.png"></a>
                            <a href="javascript:void(0);" @click="choosePayWay(7)" id="cash" class="button"><img class="payWayIcon" src="${contextPath}/static/image/payWayImage/cash.png"></a>
                        </div>
                        <div id="changeRow" class="row hide">
                            <div class="table-responsive" style=" margin: 20px auto; text-align: center; border: dashed 1px #000000; width: 90%; border-radius: 10px;">
                                <table class="table">
                                    <caption>找零</caption>
                                    <tbody>
                                    <tr>
                                        <td>应收</td>
                                        <td>实收</td>
                                        <td>找零</td>
                                    </tr>
                                    <tr>
                                        <td>￥<new id="amtHtml">{{accSub(totalAmt , befAmt)}}</new>元</td>
                                        <td>
                                            ￥<input type="text" id="changeM" style="border-bottom: solid 1px #000000; border-style:none none solid none;
                                background-color:transparent; width: 50px; text-align: right;">元
                                        </td>
                                        <td>￥<new id="change">0</new>元</td>
                                    </tr>
                                    </tbody>
                                </table>
                                <div style="margin-top: 20px; text-align: right; margin-right: 15px; margin-bottom: 5px;">
                                    <button type="button" id="buttonChange" class="btn btn-success" name="" @click="choosePayWay(7)">确定</button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" @click="cancelPayOrder" class="btn btn-default">取消</button>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal-dialog -->
        </div><!-- /.modal -->
        <!-- 支付二维码展示区域 -->
        <div id="payQrCodeContent" style="text-align: center;" class="hide">
            <div style="margin-top: 40px;" id="pay_qr_code"></div>
            <div style="margin-top: 20px;"><span style="color: red;font-size: 20px;">￥{{accSub(totalAmt , befAmt)}}元</span></div>
            <%--<div style="margin-top: 20px;">--%>
            <%--<button type="button" id="buttonCode" class="btn btn-success" name="" @click="choosePayWay(100)">确定支付</button>--%>
            <%--<button type="button" id="qxbuttonCode" class="btn btn-success" name="" @click="choosePayWay(10)">取消</button>--%>
            <%--</div>--%>
        </div>

        <!-- 刮刮奖二维码展示区域 -->
        <div id="guaQrCodeContent"
             style="text-align: center;
                     background-image: url('${contextPath}/static/image/qr_bg_pic.png');
                     filter:'progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=\'scale\')';
                     -moz-background-size:100% 100%;
                     background-size:100% 100%;"
             class="hide">
            <div style="padding-top: 159px" id="gua_qr_code"></div>
        </div>


        <!-- 价格展示区域 -->
        <div id="priceContent" class="hide" style="font-size: 18px;">
            <div style=" margin: 20px auto; border: dashed 1px #000000; width: 300px; border-radius: 10px; ">
                <div style="width: 200px; margin: 0 auto;">
                    <div class="radio" id="price1">
                        <label>
                            <input type="radio" name="optionsRadios" id="optionsRadios1" value="" checked>
                            零售价：￥<new id="rtlPrice"></new>元
                        </label>
                    </div>
                    <div class="radio" id="price2">
                        <label>
                            <input type="radio" name="optionsRadios" id="optionsRadios2" value="">
                            团购价：￥<new id="dispatchPrice"></new>元
                        </label>
                    </div>
                    <div class="radio" id="price3">
                        <label>
                            <input type="radio" name="optionsRadios" id="optionsRadios3" value="">
                            会员价：￥<new id="vipPrice"></new>元
                        </label>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

</body>
<script src="${contextPath}/static/statistics/js/jquery.js"></script>
<script src="${contextPath}/static/statistics/js/bootstrap.min.js"></script>
<script src="${contextPath}/static/supermarket/jquery.qrcode.min.js"></script>
<script src="${contextPath}/static/supermarket/guid.js"></script>
<script src="${contextPath}/static/supermarket/supermarketparams.js"></script>
<script src="${contextPath}/static/statistics/js/vue.js"></script>
<script src=${contextPath}/static/layer/layer.js></script>
<%--<script src="https://unpkg.com/axios@0.12.0/dist/axios.min.js"></script>
<script src="https://unpkg.com/lodash@4.13.1/lodash.min.js"></script>--%>
<script src="${contextPath}/static/supermarket/axios.min.js"></script>
<script src="${contextPath}/static/supermarket/lodash.min.js"></script>
<script src="${contextPath}/static/supermarket/home.js"></script>
<script type="text/javascript">

    var context_Path = '${contextPath}'
    var shopType = '${user.shopType}';
    var ind;
    var vife = true;
    var anCode = 1;
    var weiCode = 1;
    var payType = 7;
    var keyCodes = 0;
    var anCodeYz = false;
    var confirmOrderYz = true;

    if(shopType == '直营' || shopType == '加盟'){
        $("#changeRow").removeClass("hide");
    }



    $(document).keyup(function(event){
        keyCodes = event.keyCode;
        console.log(anCodeYz +"   "+ confirmOrderYz+'    '+ anCode)
//        console.log(keyCodes)
//        if(keyCodes != 13){
//            anCode = 1;
//        }

//        if(event.keyCode ==13 && anCode == 6) {
//            anCode = 1;
//            console.log(anCode)
//            anCode++;
//            app.getPayQrCodeFn(7) //实际上是去请求支付
//            layer.close(ind);
//            return;
//        }
////        if(event.keyCode ==13 && anCode == 6) {
////            console.log(anCode)
////            anCode++;
////            app.choosePayWay('7')
////            return;
////        }
//        if(event.keyCode ==13 && anCode == 4){
//            console.log(anCode)
//            anCode++;
//            $("#guaQrCodeContent").removeClass('hide');
//            app.choosePayWay(7);
//            return;
//        }
//        if(event.keyCode ==13 && anCode == 2){
//            anCode++;
//            app.confirmOrder();
//            return;
//        }

//        if(event.keyCode ===  13  && anCode === 2 && anCodeYz){
//            anCode = 1;
//            console.log('确定现金收款回');
//            $('#cash').focus();
//            app.choosePayWay(7);
//        }

        if(event.keyCode ===  13 && anCode === 2 && confirmOrderYz){
            anCode = 1;
            console.log('确定结算回车')
            $('#confirmOrder').focus();
            app.confirmOrder();
        }
        if(event.keyCode ===  13){
            anCode++;
        }else {
            confirmOrderYz = true;
            anCode = 1;
        }
    });

    //onkeydown() //监听键盘事件
    var onTQuantityKeyDown = function(id) {
        var quantityId = "#"+id;
        var stock = $(quantityId).attr('name');
        //console.log(event.keyCode);
        if (event.keyCode == 107) {
            event.preventDefault(); //禁止默认事件（默认是换行）
            var quantity = Number($(quantityId).html());
            //console.log(quantity + 1)
            if (quantity + 1 <= stock){
                $(quantityId).html(quantity + 1);
            }else {
                $(quantityId).html('');
                layer.msg("提示：数量不能大于库存量！");
            }
        }
        if (event.keyCode == 109) {
            event.preventDefault(); //禁止默认事件（默认是换行）
            var quantity = $(quantityId).html();
            if (quantity - 1 > 0){
                $(quantityId).html(quantity - 1);
            }else {
                layer.msg("提示：数量不能小于0！");
            }
        }
    }

    $(function () {
        app.getSalesStatistics();
        $('#barCodeInput').focus();
    })

    /*** input 实时监控 *****/
    $('#changeM').bind('input propertychange', function() {
        var pattern = /^(\-|\+)?\d+(\.\d+)?$/;
        var changeM = Number($("#changeM").val());
        if(!pattern.test(changeM)){
            layer.msg('提示：输入有误！');
            $("#changeM").val('');
            $("#change").html(0);
            return
        }
        var amt = Number($("#amtHtml").html());
        if(changeM - amt>0){
            $("#change").html((changeM - amt).toFixed(2));
        }else {
            $("#change").html(0);
        }
    });


    $('#privilege_amt_input').bind('input propertychange', function() {
        var d = $('#privilege_amt_input').val();
        if (Number(app.totalAmt) <= 0) {
            console.log(d);
            app.befAmt = '';
            $('#privilege_amt_input').attr('placeholder','优惠额');
        }
    })
</script>

<script src="${contextPath}/static/usrCloud/web/mqttws31.js"></script>
<script src="${contextPath}/static/usrCloud/web/usrCloud.js"></script>
<%--//透传云--%>
<script lang="javascript">

    var interval;
    var account = '356566078061470';
    var arrayObj = new Array();
    //透传云

    /**
     * 登陆（云组态和云交换机共用）
     */
    function connect(account,password) {
        console.log('登陆');
        console.log('账号：'+account+ '    密码：'+password);
        usrCloud.USR_Connect(account, hex_md5(password));
    }

    /**
     * 取消登录（云组态和云交换机共用）
     */
    function disConnect() {
        usrCloud.USR_DisConnect();
    }

    /**
     * 连接成功回调（云组态和云交换机共用）
     */
    function USR_onConnAck(event) {
        if(event.code==0) {
            console.log("连接成功");
            subscribeDevRaw(account);
        }else{
            console.log("连接失败");
        }
    }

    /**
     * 连接丢失回调（云组态和云交换机共用）
     */
    function USR_onConnLost(event) {
        console.log("连接断开，重新连接！");
        connect('test2', '123456');
    }

    /**
     * 订阅成功回调（云组态和云交换机共用）
     */
    function USR_onSubscribeAck(event) {
        console.log(event);
        //判断返回函数名
        if (event.SubFunName === 'SubscribeDevParsed') { //云组态
            if (event.code === 0) {
                console.log('订阅成功');
                $("#topic1").append("<li>" + event.SubParam.split('/')[2] + "</li>");
            } else {
                console.log('订阅失败');
            }
        } else if (event.SubFunName === 'SubDevRaw' || event.SubFunName === 'SubscribeUserRaw' || event.SubFunName === 'UnSubscribeDevRaw') { //云交换机
            if (event.code === 0) {
                $("#topic2").append("<li>" + event.SubParam.split('/')[2] + "</li>");
                console.log('订阅成功');
            } else {
                console.log('订阅失败');
            }
        }
    }

    /**
     * 取消订阅成功回调（云组态和云交换机共用）
     */
    function USR_onUnSubscribeAck(event) {
        if (event.SubFunName === 'UnSubscribeDevParsed') { //云组态
            if (event.code === 0) {
                console.log('取消订阅成功');
                $("#topic1 li").each(function () {
                    if ($(this).text() === event.SubParam.split('/')[2]) {
                        $(this).remove();
                    }
                })
            } else {
                console.log('取消订阅失败');
            }
        } else if (event.SubFunName === 'UnSubDevRaw' || event.SubFunName === 'UnSubscribeUserRaw' || event.SubFunName === 'UnSubscribeDevRaw') { //云交换机
            if (event.code === 0) {
                console.log('取消订阅成功');
                //遍历删除已取消订阅的设备
                $("#topic2 li").each(function () {
                    if ($(this).text() === event.SubParam.split('/')[2]) {
                        $(this).remove();
                    }
                })
            } else {
                console.log('取消订阅失败');
            }
        }
    }


    /**
     * 数据点数据推送回调（云组态）
     */
//todo 看一下返回的字段
    function USR_onRcvParsedDataPointPush(event) {
        for(let i in event.dataPoints){
            $("#rcvCount1").text(parseInt($("#rcvCount1").text())+1);
            $("#rcvData1").append("<li>devId:" + event.devId +"slaveIndex"+event.dataPoints[i].slaveIndex+ " dataPointId:" + event.dataPoints[i].pointId + " value:" + event.dataPoints[i].value);
        }
    }

    /**
     * 接收数据状态回调（云组态）
     */
    function USR_onRcvParsedOptionResponseReturn(event) {
        $("#rcvCount1").text(parseInt($("#rcvCount1").text())+1);
    }

    /**
     * 接收上下线回调（云组态）
     */
    function USR_onRcvParsedDevStatusPush(event) {
        $("#rcvCount1").text(parseInt($("#rcvCount1").text())+1);
        alert('devId:' + event.devId + 'status:' + event.status);
    }

    /**
     * 接收设备报警回调（云组态）
     */
    function USR_onRcvParsedDevAlarmPush(event) {
        $("#rcvCount1").text(parseInt($("#rcvCount1").text())+1);
    }

    var yzCode = 0;
    var getProdCode = function () {
        console.log('监控条码数组')
        if (arrayObj.length >= 1 && arrayObj.length == yzCode) {
            console.log('数组没有变化执行')
            console.log(arrayObj)
            clearInterval(interval);
            for (var i = 0; i < arrayObj.length; i++) {
                console.log('商品条码: '+arrayObj[i])
                $("#barCodeInput").val(arrayObj[i]);
//                app.barCode = arrayObj[i];
//                app.getProductInfo();

                var data = {
                    url: getProductByBC,
                    stringMap: {
                        barCode: arrayObj[i],
                        shopId: $("#shop_id").val()
                    }
                }
                console.log(data);
                $.ajax({
                    url: context_Path + '/supermarket/httpPost',
                    type: 'post',
                    dataType: 'json',
                    data: data,
                    success: function (data) {
                        anCode = 1;
                        layer.closeAll('loading')
                        $("#barCodeInput").val('');
                        ////console.log(data)
                        if (data.code != '000') {
                            layer.msg(data.exception)
                            return
                        }

                        var arrayData = data.data;

                        var quantity = arrayData.quantity;
                        var quan = quantity == null ? 1 : quantity;
                        ////console.log(prod)
                        var barCode = arrayData.barCode;

                        if (barCode) {
                            for (ind in app.productList) {
                                var prod = app.productList[ind]
                                // //console.log(prod)
                                if (prod.barCode == barCode) {
                                    //console.log('==========>'+prod.quantity +'   '+ quan)
                                    quan = parseInt(prod.quantity) + parseInt(quan);
                                    app.productList.splice(ind, 1)
                                    break;
                                }
                            }
                        }
                        arrayData.quantity = quan
                        console.log('商品信息')
                        console.log(arrayData)
                        arrayData.rtlPrices = arrayData.rtlPrice;

                        app.productList.splice(0, 0, arrayData);
                        //console.log(app.productList)
                        app.barCode = ''
                    },
                    error: function (error) {
                        anCode = 1;
                        $("#barCodeInput").val('');
                        layer.closeAll('loading')
                        layer.msg('网络错误')
                    }
                })

                if(i == arrayObj.length-1){
                    console.log('重新执行数组监控')
                    arrayObj = [];
                    interval = setInterval(function () {
                        getProdCode()
                    }, 5000);
                }
            }
        } else {
            console.log('数组长度变化' + arrayObj.length)
            yzCode = arrayObj.length;
        }
    }


    /**
     * 接收设备原始数据流回调（云交换机）
     */
    function USR_onRcvRawFromDev(event) {
        console.log('设备ID:'+event['devId']+'   数据：'+UTF8ToString(event.payload, 0, event.payload.length));
        var prodCode = UTF8ToString(event.payload, 0, event.payload.length);
//        var arrayObj = new Array();
        arrayObj.push(prodCode);// 将一个或多个新元素添加到数组结尾，并返回数组新长度
//        console.log(arrayObj);
//        interval = setInterval(function () {
//            getProdCode(arrayObj)
//        }, 2000);
    }


    var usrCloud = new UsrCloud();
    //定义回调
    var callback = {
        USR_onConnAck: USR_onConnAck,
        USR_onConnLost: USR_onConnLost,
        USR_onSubscribeAck: USR_onSubscribeAck,
        USR_onUnSubscribeAck: USR_onUnSubscribeAck,
        USR_onRcvParsedDataPointPush: USR_onRcvParsedDataPointPush,
        USR_onRcvParsedOptionResponseReturn: USR_onRcvParsedOptionResponseReturn,
        USR_onRcvParsedDevStatusPush: USR_onRcvParsedDevStatusPush,
        USR_onRcvRawFromDev: USR_onRcvRawFromDev,
        USR_onRcvParsedDevAlarmPush: USR_onRcvParsedDevAlarmPush
    };
    //初始化
    usrCloud.Usr_Init("clouddata.usr.cn", 8080, 2, callback);

    /**
     * 订阅设备数据
     */
    function subscribeDevParsed() {
        var result = usrCloud.USR_SubscribeDevParsed($("#devId").val());
        if (result !== 0) {
            console.log('订阅失败,错误代码：' + result);
        }
    }

    /**
     * 取消订阅设备数据（云组态）
     */
    function unSubscribeDevParsed() {
        var result = usrCloud.USR_UnSubscribeDevParsed($("#devId").val());
        if (result !== 0) {
            console.log('取消订阅失败,错误代码：' + result);
        }
    }

    /**
     * 读取数据点数据
     */
    function publishParsedQueryDataPoint(){
        var result = usrCloud.USR_PublishParsedQueryDataPoint($("#devId").val(), $("#dataPointId").val());
        if (result === 0) {
            $("#sendCount1").text(parseInt($("#sendCount1").text())+1);
            $("#info5").text("");
            $("#sendData1").append("<li>devId:" + $("#devId").val() + " dataPointId:" + $("#dataPointId").val()+"</li>");
        } else {
            $("#info5").text("发送失败");
        }
    }


    /**
     * 设置数据点数据（云组态）
     */
    function publishParsedSetDataPoint() {
        var result = usrCloud.USR_PublishParsedSetSlaveDataPoint($("#devId").val(), $("#slaveIndex").val(),$("#dataPointId").val(), $("#value").val());
        if (result === 0) {
            $("#sendCount1").text(parseInt($("#sendCount1").text())+1);
            $("#info5").text("");
            $("#sendData1").append("<li>devId:" + $("#devId").val() + " slaveIndex:" + $("#slaveIndex").val() + " dataPointId:" + $("#dataPointId").val() + " value:" + $("#value").val()+"</li>");
        } else {
            $("#info5").text("发送失败");
        }
    }

    /**
     * 订阅设备原始数据流（云交换机）
     */
    function subscribeDevRaw(account) {
        var result;
//        if ($("#accountsub").is(":checked")) { //订阅账号下全部设备
//            result = usrCloud.USR_SubscribeUserRaw($("#account").val());
//        } else { //取消订阅单个设备
        result = usrCloud.USR_SubscribeDevRaw(account);
//        }
        if(result == '0'){
            console.log("订阅成功");
        }else {
            console.log("订阅失败，错误代码:" + result);
        }
    }

    /**
     * 取消订阅设备原始数据流（云交换机）
     */
    function unSubscribeDevRaw() {
        var result;
        if ($("#devicesub").is(":checked")) { //订阅账号下全部设备
            result = usrCloud.USR_UnSubscribeDevRaw($("#devId2").val());
        } else { //取消订阅单个设备
            result = usrCloud.USR_UnSubscribeUserRaw($("#account").val());
        }
        console.log("取消订阅失败，错误代码:" + result);
    }

    /**
     * 发送原始数据流（云交换机）
     */
    function publishRawToDev() {
        var dataByte = [];
        var devId = $('#publishTopic').val();
        var payload = $('#publishPayload').val();
        if ($('#isPubHex').is(':checked')) {
            //十六机制字符串转Uint8Array格式的字节数组
            dataByte = HexStr2Bytes(payload);
            console.log('dataByte: '+dataByte);
        } else {
            //获取消息UTF-8编码字节长度并创建Uint8Array字节数组
            for (var i = 0; i < payload.length; i++) {
                dataByte[i] = payload.charCodeAt(i);
            }
            stringToUTF8(payload, dataByte, 0);
        }
        var result;
        if ($("#devicepub").is(':checked')) { //向单个设备发送
            result = usrCloud.USR_PublishRawToDev(devId, payload);
            if (result === 0) {
                $("#sendData2").append("<li>devId:" + devId + " data:" + payload);
            }
        } else { //向账号下全部设备发送
            result = usrCloud.USR_PublishRawToUser($("#account").val(), payload);
            if (result === 0) {
                $("#sendData2").append("<li>username:" + $("#account").val() + " data:" + payload);
            }
        }
        if (result !== 0) {
            $("#info4").text("发送失败");
        } else {
            $("#info4").text("");
            $("#sendCount2").text(parseInt($("#sendCount2").text())+1);
        }
    }

    function clear1() {
        $("#sendData1").html("");
        $("#sendCount1").text(0);
    }
    function clear2() {
        $("#rcvData1").html("");
        $("#rcvCount1").text(0);
    }


    function clear3() {
        $("#sendData2").html("");
        $("#sendCount2").text(0);
    }
    function clear4(){
        $("#rcvData2").html("");
        $("#rcvCount2").text(0);
    }


    $(function () {
        var shopId = $("#shop_id").val();
        if(shopId == '3318' || shopId == '3621' || shopId == '3944' || shopId == '25997'){
            console.log(shopId)
            connect('SAE_JAY', 'SAE123456');

//            arrayObj = [6901028221207,6901028037051,6901028037051,6901028037921,6901028037921]
            interval = setInterval(function () {
                getProdCode()
            }, 3000);
        }
    })
</script>
</html>





